<template>
  <div class="wraper">
    <el-row :gutter="10" style="padding-bottom: 20px;">
      <el-col :span="16">
        <el-button type="primary" @click="add">新增</el-button>
        <el-button type="primary" @click="edit">编辑勾选</el-button>
        <el-button type="primary" @click="deletebtn">删除勾选</el-button>
      </el-col>

      <div style="float:right">
        <el-input
          v-model.trim="dataForm.keyword"
          placeholder="请输入单行文本"
          clearable
          :style="{ width: '200px', marginRight: '10px' }"
        >
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
        <el-button type="primary" @click="search">搜索</el-button>
        <el-button type="primary" @click="resetSearch" v-show="isShowReset"
          >清空搜索</el-button
        >
      </div>
    </el-row>
    <el-table
      @selection-change="selectChange"
      ref="singleTable"
      :data="tableData"
      @cell-click="tabClick"
      style="width: 100%"
      v-loading="loading"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      highlight-current-row
      @current-change="handleCurrentRowChange"
    >
      <el-table-column
        type="index"
        label="序号"
        fixed
        width="50"
        :index="indexMethod"
        align="center"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column type="selection" align="center" width="55">
      </el-table-column>
      <template v-for="(item, idx) in option">
        <el-table-column
          :prop="item"
          :key="idx"
          :label="formatter(item)"
          min-width="120"
          align="center"
          sortable
        >
          <template slot-scope="scope">
            <template v-if="item === 'id'">
              <el-tag type="primary" disable-transitions>{{
                scope.row[item]
              }}</el-tag>
            </template>

            <template v-else-if="item === 'channel'">
              <el-input
                v-if="scope.row.id === tabClickIndex && item === tabClickLabel"
                v-model.trim="scope.row[item]"
                placeholder="请输入"
                maxlength="300"
                @blur="inputBlur"
              />
              <p class="value" v-else>
                {{ scope.row[item] }}
              </p>
            </template>
            <template v-else-if="item === 'status'">
              <template v-if="scope.row[item] == 0">
                <el-tag disable-transitions> 待确认 </el-tag>
              </template>
              <template v-else-if="scope.row[item] == 1">
                <el-tag disable-transitions type="info"> 已确定 </el-tag>
              </template>
              <template v-else-if="scope.row[item] == 2">
                <el-tag disable-transitions type="warning">
                  进行中
                </el-tag>
              </template>
              <template v-else-if="scope.row[item] == 3">
                <el-tag disable-transitions type="success"> 已完成 </el-tag>
              </template>
              <template v-else>
                <el-tag disable-transitions type="danger"> -- </el-tag>
              </template>
            </template>
            <template v-else-if="item === 'take_time'">
              <el-tooltip
                class="item"
                effect="dark"
                :content="formatDate(scope.row[item])"
                placement="top"
              >
                <el-tag type="success">
                  {{ scope.row[item] | formatDate | formatTime }}
                </el-tag>
              </el-tooltip>
            </template>
            <template v-else-if="item === 'admin_name'">
              <el-tooltip
                class="item"
                effect="dark"
                :content="scope.row[item]"
                placement="top"
              >
                <div
                  style="
                    display: flex;
                    align-items: center;
                    justify-content: center;
                  "
                >
                  <el-avatar
                    icon="el-icon-user-solid"
                    style="margin-right: 10px"
                  ></el-avatar>
                  {{ scope.row[item] }}
                </div>
              </el-tooltip>
            </template>
            <template v-else>
              <el-input
                v-if="scope.row.id === tabClickIndex && item === tabClickLabel"
                v-model.trim="scope.row[item]"
                placeholder="请输入"
                maxlength="300"
                @blur="inputBlur"
              />
              <p class="value" v-else>
                {{ scope.row[item] }}
              </p>
            </template>
          </template>
        </el-table-column>
      </template>
      <el-table-column
        fixed="right"
        align="center"
        label="操作"
        min-width="100"
      >
        <template slot-scope="scope">
          <el-button
            @click="handleView(scope.row.id, 'view')"
            type="text"
            size="small"
            >查看</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="edit(scope.row.id, 'single')"
            >编辑</el-button
          >
          <el-button
            @click="deletebtn(scope.row.id, 'single')"
            type="text"
            size="small"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      style="margin-top: 30px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="dataForm.page"
      :page-sizes="pageSizes"
      :page-size="dataForm.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
    <el-dialog
      :title="dialogTip"
      v-dialogDrag
      :visible.sync="dialogVisible"
      width="776px"
    >
      <el-form ref="form" :model="form" size="small" label-width="80px">
        <el-form-item label="工单标题">
          <div v-if="readOnly" class="typeView">{{ form.name }}</div>
          <el-input v-model.trim="form.name" clearable v-else></el-input>
        </el-form-item>
        <el-form-item label="工单来源">
          <div v-if="readOnly" class="typeView">{{ form.channel }}</div>
          <el-select
            v-else
            v-model.trim="form.channel"
            filterable
            clearable
            allow-create
            :style="{ width: '100%' }"
            default-first-option
            placeholder="工单来源"
          >
            <el-option
              v-for="item in selectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="销售人员">
          <div v-if="readOnly" class="typeView">{{ form.admin_name }}</div>
          <el-select
            v-else
            v-model.trim="form.admin_name"
            filterable
            clearable
            allow-create
            default-first-option
            :style="{ width: '100%' }"
            placeholder="销售人员"
          >
            <el-option
              v-for="item in personOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="接单时间">
          <div v-if="readOnly" class="typeView">
            {{ form.take_time | formatDate }}
          </div>
          <el-date-picker
            :popper-append-to-body="false"
            v-else
            v-model="form.take_time"
            clearable
            type="datetime"
            :style="{ width: '100%' }"
            format="yyyy-MM-dd hh:mm:ss A"
            value-format="timestamp"
            placeholder="选择日期时间"
            align="right"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="订单状态">
          <div v-if="readOnly" class="typeView">
            <template v-if="form.status === 0">
              待确认
            </template>
            <template v-else-if="form.status === 1">
              已确定
            </template>
            <template v-else-if="form.status === 2">
              进行中
            </template>
            <template v-else>
              已完成
            </template>
          </div>
          <el-radio-group v-else v-model="form.status">
            <el-radio :label="0">待确认</el-radio>
            <el-radio :label="1">已确定</el-radio>
            <el-radio :label="2">进行中</el-radio>
            <el-radio :label="3">已完成</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="内容">
          <div
            v-if="readOnly"
            class="typeView ql-editor"
            v-html="$xss(form.content)"
          ></div>
          <div style="height:315px;" v-else>
            <quill-editor
              style="height:220px;"
              ref="myTextEditor"
              v-model="form.content"
              :options="editorOption"
            ></quill-editor>
          </div>
        </el-form-item>
        <!-- {{ form.content }} -->
        <el-form-item align="right" style="margin-left:-80px">
          <el-button type="primary" @click="onSubmit" v-if="!readOnly"
            >提交</el-button
          >
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import { deepClone, formatDate } from "@/utils/index";
import { quillEditor } from "vue-quill-editor";
export default {
  data() {
    return {
      isShowReset: false,
      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            }
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            }
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            }
          }
        ]
      },
      editorOption: {
        placeholder: "编辑文章内容"
      },
      dialogVisible: false, //弹窗
      readOnly: false, //弹窗是否只读
      tabClickIndex: null, // 点击的单元格
      tabClickLabel: "", // 当前点击的列名
      tableData: [],
      selectArray: [], //选中项
      loading: true,
      option: [], //表头
      oldValue: null,
      dialogTip: "提示",
      pageSizes: [5, 10, 20, 100, 200, 300],
      personOptions: [
        {
          value: "张山",
          label: "张山"
        },
        {
          value: "李时",
          label: "李时"
        },
        {
          value: "王武",
          label: "王武"
        }
      ],
      selectOptions: [
        {
          value: "线上",
          label: "线上"
        },
        {
          value: "线下",
          label: "线下"
        }
      ],
      total: 0, //一共多少条
      dataForm: {
        page: 1, //当前页: ${val}
        pagesize: 10, //每页 ${val} 条
        keyword: ""
      },
      form: {
        id: "",
        name: "",
        channel: "",
        admin_name: "",
        take_time: "",
        status: "",
        content: ""
      },
      initForm: {
        name: "",
        channel: "",
        admin_name: "",
        take_time: "",
        status: "",
        content: ""
      }
    };
  },
  watch: {
    dialogVisible(val) {
      if (val === false) {
        this.$nextTick(() => {
          setTimeout(() => {
            this.readOnly = false;
          }, 500);
        });
      }
    }
  },
  components: {
    quillEditor
  },
  // directives: {
  //   focus: {
  //     inserted: function (el) {
  //       el.querySelector("input").focus();
  //     },
  //   },
  // },
  created() {
    this.getSearchList();
  },
  filters: {
    formatDate(time) {
      time = time * 1;
      let date = new Date(time);
      return formatDate(date, "yyyy-MM-dd");
    },
    formatTime: function(value) {
      //date1和date2是2002-12-18格式
      var date1Str = value.split("-"); //将日期字符串分隔为数组,数组元素分别为年.月.日
      var date1Obj = new Date(date1Str[0], date1Str[1] - 1, date1Str[2]);
      // var date2Str = date2.split("-");
      var date2Obj = new Date();
      var t1 = date1Obj.getTime();
      var t2 = date2Obj.getTime();
      var dateTime = 1000 * 60 * 60 * 24; //每一天的毫秒数
      var minusDays = Math.floor((t2 - t1) / dateTime); //计算出两个日期的天数差
      var days = Math.abs(minusDays); //取绝对值
      if (days === 0) {
        return "当天";
      }
      if (days > 30) {
        if (days > 365) {
          if (days > 36500) {
            return (
              Math.floor(days / 36500) +
              "世纪" +
              Math.floor((days % 36500) / 365) +
              "年前"
            );
          }
          return (
            Math.floor(days / 365) +
            "年" +
            Math.floor((days % 365) / 30) +
            "月前"
          );
        }
        return Math.floor(days / 30) + "月前";
      }
      return days + "天前";
    }
  },
  methods: {
    resetSearch() {
      this.dataForm.keyword = "";
      this.dataForm.page = 1;
      this.getSearchList().then(res => {
        console.log(res);
        this.isShowReset = false;
        // console.log(this);
      });
    },
    formatDate(time) {
      time = time * 1;
      let date = new Date(time);
      return formatDate(date, "yyyy-MM-dd");
    },
    escapeStringHTML(str) {
      str = str.replace(/&lt;/g, "<");
      str = str.replace(/&gt;/g, ">");
      return str;
    },
    onEditorChange({ editor, html, text }) {
      this.form.content = html;
    },
    onSubmit() {
      // 没有id则是add 新增
      let value = deepClone(this.form);
      delete value.id;
      if (this.form.id) {
        this.$api
          .edit({ id: this.form.id, value: JSON.stringify(value) })
          .then(res => {
            if (res && res.data.code === 0) {
              this.$message({
                message: res.data.message,
                type: "success"
              });
              this.dialogVisible = false;
              //编辑不用回到第一页
              this.getSearchList();
            } else {
              this.$message.error(res.data.message);
            }
          });
      } else {
        this.$api.add({ value: JSON.stringify(value) }).then(res => {
          if (res && res.data.code === 0) {
            this.$message({
              message: res.data.message,
              type: "success"
            });
            this.dialogVisible = false;
            this.dataForm.page = 1;
            this.getSearchList();
          } else {
            this.$message.error(res.data.message);
          }
        });
      }
    },
    async search() {
      if (this.dataForm.keyword) {
        this.isShowReset = true;
        this.dataForm.page = 1;
        await this.getSearchList().then(res => {
          this.$message({
            message: `查到符合条件的数据共${res}`,
            type: "success"
          });
        });
      } else {
        this.$message({
          message: "请输入搜索词",
          type: "warning"
        });
      }
    },
    // 新增
    add() {
      this.dialogTip = "新增";
      this.dialogVisible = true;
      this.form = deepClone(this.initForm);
    },
    handleView(val, type) {
      this.edit(val, type);
    },
    edit(val, type) {
      let paramid = "";
      if (type === "single" || type === "view") {
        if (val) {
          paramid = val;
        } else {
          this.$message({
            message: "无效id",
            type: "warning",
            duration: 1000
          });
          return;
        }
      } else {
        if (this.selectArray.length === 0) {
          this.$message({
            message: "请先勾选",
            type: "warning",
            duration: 1000
          });
          return;
        } else if (this.selectArray.length > 1) {
          this.$message({
            message: "只能勾选一条",
            type: "warning",
            duration: 1000
          });
          return;
        }
        paramid = this.selectArray[0];
      }
      this.form.id = paramid;
      if (type === "view") {
        this.dialogTip = "查看";
        this.readOnly = true;
      } else {
        this.dialogTip = "修改";
      }
      this.dialogVisible = true;
      this.$api.detail({ id: paramid }).then(res => {
        if (res && res.data.code === 0) {
          this.form = res.data.data[0];
        } else {
          this.$message.error("请求失败");
        }
      });
    },
    deletebtn(val, type) {
      let paramid = "";
      if (type === "single") {
        if (val) {
          paramid = val;
        } else {
          this.$message({
            message: "无效id",
            type: "warning",
            duration: 1000
          });
          return;
        }
      } else {
        if (this.selectArray.length === 0) {
          this.$message({
            message: "请先勾选",
            type: "warning",
            duration: 1000
          });
          return;
        } else {
          paramid = this.selectArray.join(",");
        }
      }

      this.$api.delete({ id: paramid }).then(res => {
        if (res && res.data.code === 0) {
          this.$message({
            message: "删除成功",
            type: "success",
            duration: 1000
          });
          this.dataForm.page = 1;
          this.getSearchList();
        } else {
          this.$message({
            message: res.data.message,
            type: "warning",
            duration: 1000
          });
        }
      });
    },
    tabClick(row, column, event, cell) {
      if (column.label) {
        this.tabClickIndex = row.id;
        this.tabClickLabel = column.property;
        this.oldValue = row[column.property];
      } else {
        this.tabClickIndex = null;
        this.tabClickLabel = "";
      }
    },
    //输入完成
    inputBlur(row, event, column) {
      // console.log(row,event,column);
      console.log(row.target.value, this.tabClickIndex, this.tabClickLabel);
      if (row.target.value !== this.oldValue) {
        let value = {};
        value[this.tabClickLabel] = row.target.value;
        this.$api
          .edit({ id: this.tabClickIndex, value: JSON.stringify(value) })
          .then(res => {
            if (res && res.data.code === 0) {
              this.$message({
                message: "修改成功",
                type: "success",
                duration: 1000
              });
            } else {
              this.$message({
                message: res.data.message,
                type: "warning",
                duration: 1000
              });
            }
          });
      }
      this.tabClickIndex = null;
      this.tabClickLabel = "";
    },
    selectChange(e) {
      // 选择id数组
      console.log(e);
      let array = [];
      if (e && e.length > 0) {
        e.map(item => {
          array.push(item.id);
        });
      }
      this.selectArray = array;
    },

    formatter(item) {
      //转义
      let state = {
        name: "工单标题",
        id: "ID",
        channel: "工单来源",
        admin_name: "销售",
        take_time: "接单时间",
        status: "状态"
      };
      if (Object.keys(state).indexOf(item) > -1) {
        return state[item];
      }
      return item;
    },
    async getSearchList() {
      this.loading = true;
      await this.$api.search(this.dataForm).then(res => {
        if (res && res.data.code === 0) {
          //请求成功
          if (res.data.data && res.data.data.length > 0) {
            //有数据
            if (this.option.length === 0) {
              this.option = Object.keys(res.data.data[0]); //表头
            }
            this.tableData = res.data.data;
          } else {
            this.tableData = [];
            this.$message({
              message: "暂无数据",
              type: "warning",
              duration: 1000
            });
          }
          this.total = Number(res.data.total);
          // this.tableData = res.data.data.map(item => {
          //   return { ...item, isSelected: false };
          // });
          this.$nextTick(() => {
            setTimeout(() => {
              this.loading = false;
            }, 500);
          });
        } else {
          this.$message({
            message: "查询失败",
            type: "warning",
            duration: 1000
          });
          setTimeout(() => {
            this.loading = false;
          }, 500);
        }
      });
      return this.total;
    },
    handleCurrentRowChange(val) {},
    handleSizeChange(val) {
      let oldSize = this.dataForm.pagesize; //之前
      this.dataForm.pagesize = val;
      if (this.dataForm.page * oldSize <= this.total) {
        //         this.dataForm.page*oldSize 之前浏览到的最后的位置
        if (val >= this.dataForm.page * oldSize) {
          this.dataForm.page = 1;
        } else {
          this.dataForm.page = Math.ceil((this.dataForm.page * oldSize) / val);
        }
      } else {
        //  this.dataForm.page=1
        this.dataForm.page = Math.ceil(this.total / val); //最后 一页
      }

      this.getSearchList();
    },
    handleCurrentChange(val) {
      //当前页切换
      this.dataForm.page = val;
      this.getSearchList();
    },
    indexMethod(index) {
      //序号
      return (this.dataForm.page - 1) * this.dataForm.pagesize + index + 1;
    }
  }
};
</script>
<style lang="scss" scoped>
/deep/.el-dialog__body {
  padding: 10px 20px 30px;
}
.wraper {
  padding: 20px 20px 0;
}
.typeView {
  border: 1px solid #ccc;
  padding-left: 10px;
  min-height: 30px;
  box-sizing: border-box;
  border-radius: 3px;
  box-shadow: 1px 2px 1px 0px #efefef;
  &.ql-editor {
    overflow-y: scroll;
    max-height: 300px;
  }
}
.value {
  min-height: 30px;
  min-width: 100px;
  background: inherit;
}
p:empty {
  border: 1px solid #ccc;
}
</style>
